﻿using Management.Areas.Control.Models;
using Management.Auxiliary;
using Management.Core;
using Management.Core.AdminRole;
using Management.Core.Picture;
using Management.Core.RolePermission;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Mvc;

namespace Management.Areas.Control.Controllers
{
    /// <summary>
    /// 管理员控制器
    /// </summary>
    [AdminAuthorize]
    [Description(No = 1,Name = "管理员用户")]
    public class AdminController : Controller
    {
        private AdminManager adminManager  = new AdminManager();
        private RoleManager roleManager    = new RoleManager();
        private AdminRoleManager arManager = new AdminRoleManager();
        /// <summary>
        /// 添加【Json】
        /// </summary>
        /// <param name="addAdmin"></param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        [HttpPost]
        public JsonResult AddJson(AddAdminViewModel addAdmin)
        {
            Response _res = new Response();
            if (ModelState.IsValid)
            {
                if (adminManager.HasAccounts(addAdmin.Accounts))
                {
                    _res.Code    = 0;
                    _res.Message = "帐号已存在";
                }
                else
                {
                    Admin _admin = new Admin();
                    _admin.Accounts = addAdmin.Accounts;
                    _admin.CreateTime = System.DateTime.Now;
                    _admin.Password = Security.SHA256(addAdmin.Password);
                    _admin.Email = addAdmin.Email;
                    _admin.Phone = addAdmin.Phone;
                    _admin.PictureID = 1;
                    //_admin.RoleID = RoleManager.Find(addAdmin.RoleID).RoleID;                    
                    _res = adminManager.Add(_admin);
                    AdminRole _adminrole = new AdminRole();
                    _adminrole.RoleID = 2;
                    _adminrole.AdminID = _admin.AdminID;
                    _adminrole.Created_at = DateTime.Now;
                    _adminrole.Updated_at = DateTime.Now;
                    arManager.Add(_adminrole);//新注册用户默认为普通用户
                }
            }
            else
            {
                _res.Code = 0;
                _res.Message = General.GetModelErrorString(ModelState);
            }
            return Json(_res);
        }
        /// <summary>
        /// 添加【分部视图】
        /// </summary>
        /// <returns></returns>
        public PartialViewResult AddPartialView()
        {
           
            return PartialView();
        }

        [Description(No = 1, Name = "编辑界面")]
        public ActionResult EditPartialView(int? id)
        {
            if(id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Admin admin = adminManager.Find((int)id);
            if(admin == null)
            {
                return HttpNotFound();
            }
            var _roles = roleManager.FindList();
            var tmp = admin.AdminRole.Select(r => r.RoleID).ToList();
            var adminroles = admin.AdminRole.Select(r=>r.RoleID);
            List<AssignedRoleViewModel> _listItems = new List<AssignedRoleViewModel>(_roles.Count());
            foreach (var _role in _roles)
            {
                _listItems.Add(new AssignedRoleViewModel
                {
                    AdminID = (int)id,
                    RoleID = _role.RoleID,
                    Name = _role.Name,
                    Assigned = adminroles.Contains(_role.RoleID) 
                });
                //_listItems.Add(new SelectListItem() { Text = _role.Name, Value = _role.RoleID.ToString() });
            }
            ViewBag.Roles = _listItems;

            return PartialView();
        }

        [HttpPost]
        public ActionResult EditJson(int? id, int[] selectedRoles)
        {
            Response _res = new Response();
            if (id == null)
            {
                _res.Code = -1;
                _res.Message = "error";
                return Json(_res);
            }
            var adminrole = new AdminRole();
            if (TryUpdateModel(adminrole, "", new string[] {"AdminID", "RoleID" }))
            {
                try
                {
                    //AddAdminRole(selectedRoles, (int)id);
                    if(selectedRoles == null)
                    {
                        var adminroles = arManager.FindList(u => u.AdminID == (int)id).ToList();
                        foreach (var item in adminroles)
                        {
                            arManager.Delete(u => u.AdminID == item.AdminID);
                        }
                    }
                    else
                    {
                        List<int> selectList = selectedRoles.ToList();
                        var adminRoleIDs = arManager.FindList(u => u.AdminID == (int)id).Select(r => r.AdminID).ToList();
                        var roles = roleManager.FindList().Select(u => u.RoleID).ToList();
                        foreach (var item in roles)
                        {
                            if (selectList.Contains(item))
                            {
                                if(!adminRoleIDs.Contains(item))
                                {
                                    adminrole.AdminID = (int)id;
                                    adminrole.RoleID = item;
                                    adminrole.Created_at = DateTime.Now;
                                    adminrole.Updated_at = DateTime.Now;
                                    _res=arManager.Add(adminrole);
                                }
                            }
                            else
                            {
                                _res=arManager.Delete(u => u.AdminID == (int)id && u.RoleID == item);
                            }
                        }
                    }
                    //_res.Message = "success";
                    //_res.Code = 1;
                }
                catch(Exception ex)
                {
                    _res.Code = 0;
                    _res.Message = ex.Message;
                }
            }
            return Json(_res);
        }


        /// <summary>
        /// 删除 
        /// Response.Code:1-成功，2-部分删除，0-失败
        /// Response.Data:删除的数量
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeleteJsonBatch(List<int> ids)
        {
            int _total = ids.Count();
            Response _res = new Response();
            int _currentAdminID = int.Parse(Session["AdminID"].ToString());
            if (ids.Contains(_currentAdminID))
            {
                ids.Remove(_currentAdminID);
            }
            _res = adminManager.Delete(ids);
            if (_res.Code == 1 && _res.Data < _total)
            {
                _res.Code = 2;
                _res.Message = "共提交删除" + _total + "名管理员,实际删除" + _res.Data + "名管理员。\n原因：不能删除当前登录的账号";
            }
            else if (_res.Code == 2)
            {
                _res.Message = "共提交删除" + _total + "名管理员,实际删除" + _res.Data + "名管理员。";
            }
            return Json(_res);
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        [Description(No = 1, Name = "管理员首页")]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 管理员列表
        /// </summary>
        /// <returns></returns>
        public JsonResult ListJson()
        {
            //Paging<Administrator> _pagingAdmin = new Paging<Administrator>();           
            var admins = adminManager.FindList().Select(u=>u.AdminID);
            return Json(admins);
        }
        [HttpPost]
        public ActionResult PageList(string name, int? pageNumber, int? pageSize, int? order)
        {
            Paging<Admin> _pagingAdmin = new Paging<Admin>();
            if (pageNumber != null && pageNumber > 0) _pagingAdmin.PageIndex = (int)pageNumber + 1;
            if (pageSize != null && pageSize > 0) _pagingAdmin.PageSize = (int)pageSize;
            var _paging = adminManager.FindPageList(_pagingAdmin, name, null);
            return Json(new { total = _paging.TotalNumber, rows = _paging.Items });
        }
        
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
        }

        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult Login(Management.Areas.Control.Models.LoginViewModel loginViewModel, string cnt)
        {            
            if (!string.IsNullOrEmpty(cnt))
            {
                int fieldCnt = System.Convert.ToInt32(cnt);
                if (fieldCnt > 2)
                {
                    if (Session["ValidateCode"].ToString() != loginViewModel.valicode)
                    {
                        ModelState.AddModelError("valicode", "验证码错误");
                        return View(loginViewModel);
                    }
                }
            }
            if (ModelState.IsValid)
            {
                string _passowrd = Security.SHA256(loginViewModel.Password);
                var _response = adminManager.Verify(loginViewModel.Accounts, _passowrd);
                if (_response.Code == 1)
                {
                    var _admin = adminManager.Find(loginViewModel.Accounts);
                    if(RedisHelper.Get<string>(_admin.AdminID.ToString()) != null)
                    {
                        RedisHelper.DelKey(_admin.AdminID.ToString());//先根据adminid把缓存里存sessionid的删掉
                    }
                    RedisHelper.Set<string>(_admin.AdminID.ToString(), Session.SessionID, DateTime.Now.AddHours(1) - DateTime.Now);
                    Session.Add("AdminID", _admin.AdminID);
                    Session.Add("Accounts", _admin.Accounts);
                    RoleAndPermissionCheck(_admin.AdminID);
                    //Session.Add("Role", _admin.RoleID);
                    _admin.LoginTime = DateTime.Now;
                    _admin.LoginIP = Request.UserHostAddress;
                    adminManager.Update(_admin);
                    return RedirectToAction("Index", "Home");
                }
                else if (_response.Code == 2) ModelState.AddModelError("Accounts", _response.Message);
                else if (_response.Code == 3) ModelState.AddModelError("Password", _response.Message);
                else ModelState.AddModelError("", _response.Message);
            }
            return View(loginViewModel);
        }
        
        public void RoleAndPermissionCheck(int adminid)
        {
            AdminRoleManager arm = new AdminRoleManager();
            RolePermissionManager rpm = new RolePermissionManager();
            var roles = arm.FindList(u => u.AdminID == adminid);
            List<int> permissionids = new List<int>();
            List<int> roleids = new List<int>();
            roleids = roles.Select(u => u.RoleID).ToList();
            foreach(int roleid in roleids)
            {
                var pids = rpm.FindList(u => u.RoleID == roleid);
                foreach(var pid in pids)
                {
                    permissionids.Add(pid.PermissionID);
                }
            }
            if (RedisHelper.Get<List<int>>("permissionids") != null)
            {
                RedisHelper.DelKey("permissionids");
            }
            RedisHelper.Set<List<int>>("permissionids", permissionids, DateTime.Now.AddHours(2) - DateTime.Now);
        }
        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Logout()
        {
            Session.Clear();         
            RedisHelper.DelKey("permissionids");
            return RedirectToAction("Login");
        }

        /// <summary>
        /// 我的资料
        /// </summary>
        /// <returns></returns>
        
        public ActionResult MyInfo()
        {            
            return View(adminManager.Find(Session["Accounts"].ToString()));
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult MyInfo(FormCollection form)
        {
            var _admin = adminManager.Find(Session["Accounts"].ToString());
            if (_admin.Password != form["Password"] || _admin.PictureID != int.Parse(form["PictureID"]))
            {
                _admin.Password = Security.SHA256(form["Password"]);
                _admin.PictureID = int.Parse(form["PictureID"]);
                var _resp = adminManager.ChangeInfo(_admin.AdminID, _admin.Password, _admin.PictureID);
                if (_resp.Code == 1) ViewBag.Message = "<div class=\"alert alert-success\" role=\"alert\"><span class=\"glyphicon glyphicon-ok\"></span>修改信息成功！</div>";
                else ViewBag.Message = "<div class=\"alert alert-danger\" role=\"alert\"><span class=\"glyphicon glyphicon-remove\"></span>修改信息失败！</div>";
            }
            return View(_admin);
        }

        [HttpPost]
        public ActionResult UploadThumb()
        {
            Response _resp = new Response();
            Uploader uploader = new Uploader();
            Picture p = new Picture();
            PictureManager pm = new PictureManager();
            var upFile = HttpContext.Request.Files["image"];
            int upFileLen = upFile.ContentLength;
            if (upFileLen == 0)
            {
                return JavaScript("layer.alert('没有选择上传图片'); ");
            }
            byte[] uploadFileBytes = new Byte[upFileLen];
            upFile.InputStream.Read(uploadFileBytes, 0, upFileLen);
            string sFilename = System.IO.Path.GetFileName(upFile.FileName);
            try
            {
                string OriPath   = uploader.UploadThumb(sFilename, uploadFileBytes, 0);
                string ThumbPath = uploader.UploadThumb(sFilename, uploadFileBytes, 1);
                Uploader.MakeThumbnail(OriPath, ThumbPath, 400, 400, "HW");                
                p.Path = OriPath.Remove(0, 1);
                p.ThumbPath = ThumbPath.Remove(0, 1);
                p.PicType = 0;
                p.Model = "Admin";
                p.Created_at = DateTime.Now;
                p.Updated_at = DateTime.Now;
                pm.Add(p);
                _resp.Code = 1;
                _resp.Message = ThumbPath.Remove(0, 1);
            }            
            catch (Exception ex)
            {
                _resp.Code = -1;
                _resp.Message = ex.Message;
            }
            return Json(new { result = _resp.Message, picid = p.PictureID });
        }

        /// <summary>
        /// 重置密码【123456】
        /// </summary>
        /// <param name="id">管理员ID</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ResetPassword(int id)
        {
            string _password = "123456";
            Response _resp = adminManager.ChangeInfo(id, Security.SHA256(_password),null);
            if (_resp.Code == 1) _resp.Message = "密码重置为：" + _password;
            return Json(_resp);
        }
        /// <summary>
        /// 重置密码批量【123456】
        /// 
        /// </summary>
        /// <param name="ids">管理员ID列表</param>
        /// <returns>
        /// Code：0-失败，1-成功，2-部分成功
        /// </returns>
        [HttpPost]
        public JsonResult ResetPasswordBatch(List<int> ids)
        {
            //明文密码
            string _passwordPlain = "123456";
            //密文
            string _password = Security.SHA256(_passwordPlain);
            int _total = ids.Count();
            //重置密码的数量
            int _resetNum = 0;
            //重置密码的名称
            string _resetNames = "";
            Response _resp = new Response();
            foreach (int id in ids)
            {
                _resp = adminManager.ChangeInfo(id, _password, null);
                if (_resp.Code == 1)
                {
                    _resetNum++;
                    _resetNames += "[" + _resp.Data.Accounts + "] ";
                }
            }

            if (_resetNum > 0)
            {
                if (_resetNum < _total) _resp.Code = 2;
                else _resp.Code = 1;
                _resp.Message = "共提交重置" + _total + "名管理员的密码,成功重置" + _resetNames + _resetNum + "名管理员的密码为“" + _passwordPlain + "”。";
            }
            else
            {
                _resp.Code = 0;
                _resp.Message = "重置密码失败。";
            }
            return Json(_resp);
        }

        [AllowAnonymous]
        public ActionResult ForgetPwd1(string email, string code)
        {
            Response res = new Response();
            if (Session["ValidateCode"].ToString() != code)
            {
                res.Code = 0;
                res.Message = "验证码错误";                
            }
            else
            {
                var user = adminManager.Find(u => u.Email == email);
                if(user != null)
                {
                    Random rd = new Random();
                    Session["F_Validate"] = rd.Next(1000, 9999);
                    Email.SendEmail(email, "找回密码", Session["F_Validate"].ToString());                    
                    res.Code = 1;
                    res.Message = "识别码已发送到您的邮箱，请在接下来的操作中输入该识别码";
                }
                else
                {
                    res.Code = 0;
                    res.Message = "用户不存在";
                }
            }
            return Json(res,JsonRequestBehavior.AllowGet);
        }
        [AllowAnonymous]
        public ActionResult ForgetPwd2(string f_Validate)
        {
            Response _resp = new Response();
            if (f_Validate == Session["F_Validate"].ToString())
            {
                _resp.Code = 1;                
            }
            else
            {
                _resp.Code = 0;
                _resp.Message = "识别码错误";
            }
            return Json(_resp,JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        [AllowAnonymous]
        public ActionResult ForgetPwd3(string email, string newPwd, bool flag = true)
        {
            Response _resp = new Response();
            int id = adminManager.Find(u => u.Email == email).AdminID;
            _resp = adminManager.ChangeInfo(id, Security.SHA256(newPwd), null);
            if (_resp.Code == 1) _resp.Message = "密码重置为：" + newPwd;
            return Json(_resp);
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult CetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(5);
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }

    }
}